package com.xoa.service.party;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.party.GridCheckMapper;
import com.xoa.dao.party.GridEventMapper;
import com.xoa.dao.party.GridInfoMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dev.pz.dao.MenuJdtMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.department.Department;
import com.xoa.model.party.*;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.netdisk.CheckAll;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/9/7.
 */
@Service
public class GridCheckService {
    @Autowired
    private GridCheckMapper gridCheckMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private GridInfoMapper gridInfoMapper;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private GridEventMapper gridEventMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private MenuJdtMapper menuJdtMapper;
    public BaseWrapper insertSelective(GridCheckWithBLOBs gridCheck) {
        BaseWrapper baseWrappers = new BaseWrapper();
    int conut = gridCheckMapper.insertSelective(gridCheck);
        if (conut > 0) {
            baseWrappers.setMsg("ok");
            baseWrappers.setData(gridCheck);
            baseWrappers.setFlag(true);

        } else {
            baseWrappers.setMsg("err");

            baseWrappers.setFlag(false);
        }
        return baseWrappers;
    }

    public BaseWrapper updateByPrimaryKeySelective(GridCheckWithBLOBs gridCheck) {
        BaseWrapper baseWrappers = new BaseWrapper();

        int conut = gridCheckMapper.updateByPrimaryKeySelective(gridCheck);
        if (conut > 0) {
            baseWrappers.setMsg("ok");
            baseWrappers.setData(gridCheck);
            baseWrappers.setFlag(true);

        } else {
            baseWrappers.setMsg("err");

            baseWrappers.setFlag(false);
        }
        return baseWrappers;

    }

    public BaseWrappers deleteByPrimaryKey(Integer checkId) {
        BaseWrappers baseWrappers = new BaseWrappers();

        int conut = gridCheckMapper.deleteByPrimaryKey(checkId);
        if (conut > 0) {
            baseWrappers.setMsg("ok");

            baseWrappers.setFlag(true);

        } else {
            baseWrappers.setMsg("err");

            baseWrappers.setFlag(false);
        }
        return baseWrappers;

    }

    public BaseWrapper selectByPrimaryKey(Integer checkId, HttpServletRequest request) {
        BaseWrapper baseWrappers = new BaseWrapper();
        String sqlType = "xoa"
                + (String) request.getSession().getAttribute("loginDateSouse");
        GridCheck conut = gridCheckMapper.selectByPrimaryKey(checkId);
        if(conut!=null){
            conut.setUserName(usersMapper.getUsernameByUserId(conut.getUserId()));
            if (conut.getAttachmentName() != null && conut.getAttachmentId() != null) {
                conut.setAttachments1(GetAttachmentListUtil.returnAttachment(conut.getAttachmentName(), conut.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_grid));
            }
            if (conut.getAttachmentName2() != null && conut.getAttachmentId2() != null) {
                conut.setAttachments2(GetAttachmentListUtil.returnAttachment(conut.getAttachmentName2(), conut.getAttachmentId2(), sqlType, GetAttachmentListUtil.MODULE_grid));
            }
            if(!StringUtils.checkNull(conut.getSubCommunity()))
            { conut.setInfoName(gridInfoMapper.selectByPrimaryKey(Integer.parseInt(conut.getSubCommunity())).getGridName());

            }
              GridInfo gridInfo=gridInfoMapper.selectByPrimaryKey(conut.getGridId());
               if(gridInfo!=null){
                   conut.setGridName(gridInfo.getGridName());
               }else {
                   conut.setGridName("");
               }

            conut.setCodeName(sysCodeMapper.getSingleCode("GRID_CHECK", conut.getCheckType()).getCodeName());

        }

        baseWrappers.setMsg("ok");
        baseWrappers.setData(conut);
        baseWrappers.setFlag(true);
        return baseWrappers;
    }


    public BaseWrappers selectList(HttpServletRequest request, HttpServletResponse response, String gridName, String checkType, String newsTime, String lastEditTime,
                                   String userId, String checkInfo, Integer page, Integer pageSize, String exportId, String userName
    ) {
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());

        List<GridCheck> gridChecks=new ArrayList<GridCheck>();
        BaseWrappers baseWrappers = new BaseWrappers();
        baseWrappers.setStatus(true);
        baseWrappers.setFlag(false);
        page = (page - 1) * pageSize;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("page", page);
        param.put("pageSize", pageSize);
        param.put("gridName", gridName);
        param.put("checkType", checkType);
        param.put("newsTime", newsTime);
        param.put("lastEditTime", lastEditTime);
        param.put("checkInfo", checkInfo);
        param.put("userName", userName);
        List<String> userIdList = new ArrayList<>();
        //根据userID查询该角色可以查看的巡检记录
                //先查询该角色是否有查询所有网格巡检权限
               int qx=0;
                int total=0;
                if(user.getUserPriv()!=null){
                    if(user.getUserPriv()==1 || user.getUserPriv()==2 || user.getUserPriv()==6 || user.getUserPriv()==13 || user.getUserPriv()==93 || user.getUserPriv()==4){  //|| user.getUserPriv()==104 居委会主任
                        if(userId==null || userId.equals("")){
                            param.put("StringUser",userIdList);
                            param.put("userId","");
                        }
                        if(!StringUtils.checkNull(userId)){
                            param.put("userId", userId);
                        }
                        //查询全部权限角色
                         gridChecks = gridCheckMapper.selWillGridSendOrReceive(param);
                        qx=1;
                    }else {
                        //查询自己社区权限
                        //计数器
                        List<String> stringUserId=new ArrayList<>();
                        List<Integer> string=gridInfoMapper.sQqXselectTis(user.getUserId());
                        if(string.size()==0){
                            userIdList.add(user.getUserId());
                            param.put("userId","");
                            param.put("StringUser",userIdList);
                            gridChecks = gridCheckMapper.selWillGridSendOrReceive(param);
                            total = gridCheckMapper.selWillGridSendOrReceiveCounts(param);
                        }else {
                            //根据社区查询用户
                            for(Integer grid:string){
                                GridInfo userIds=gridInfoMapper.selectByPrimaryKey(grid);
                                if(userIds!=null){
                                    stringUserId.add(userIds.getGridUserId());
                                }
                            }
                            if(userId!=null && !userId.equals("")){
                                param.put("userId",userId);
                            }
                            String tmesim="";
                            for(int cou=0;cou<stringUserId.size();cou++){
                                if(stringUserId.get(cou)!=null){
                                    if(!stringUserId.get(cou).toString().equals("''")){
                                        if(stringUserId.get(cou).substring(stringUserId.get(cou).length()-1, stringUserId.get(cou).length()).equals(",")){
                                            if(tmesim!=null && tmesim!=""){
                                                tmesim=tmesim+","+stringUserId.get(cou);
                                            }
                                        }
                                        tmesim+=stringUserId.get(cou);
                                    }
                                }
                            }
                            String[] stringList=null;
                            if(tmesim!=null){stringList = tmesim.split(",");
                            }
                            //数组去重复
                            List<String> list = new ArrayList<String>();
                            for (int i=0; i<stringList.length; i++) {
                                if(!list.contains(stringList[i])) {
                                    list.add(stringList[i]);
                                }
                            }
                                param.put("StringUser",list);
                                if(list.size()==0){
                                    list.add(user.getUserId());
                                    param.put("StringUser",list);
                                }
                                gridChecks.addAll(gridCheckMapper.selWillGridSendOrReceive(param));
                                int sum=gridCheckMapper.selWillGridSendOrReceiveCounts(param);
                                total+=sum;
                        }
                    }
                    //判断权限
                    if(qx==1){
//                        gridChecks = gridCheckMapper.selWillGridSendOrReceive(param);
                        total = gridCheckMapper.selWillGridSendOrReceiveCounts(param);
                    }
                }else {
                    userIdList.add(user.getUserId());
                    gridChecks = gridCheckMapper.selWillGridSendOrReceive(param);
                    total = gridCheckMapper.selWillGridSendOrReceiveCounts(param);
                }
//        gridChecks = gridCheckMapper.selWillGridSendOrReceive(param);
//        total = gridCheckMapper.selWillGridSendOrReceiveCounts(param);
        if(gridChecks!=null){
            if (gridChecks != null && gridChecks.size() > 0) {
                for (GridCheck g : gridChecks) {
                    if (g != null && !StringUtils.checkNull(g.getCheckType())) {
                        SysCode singleCode = sysCodeMapper.getSingleCode("GRID_CHECK", g.getCheckType());
                        if(singleCode!=null){
                            g.setCheckType(singleCode.getCodeName());
                        }else{
                            g.setCheckType("");
                        }
                    }
                }
            }

            List<GridCheck> gridCheckss=new ArrayList<GridCheck>();
            if ("1".equals(exportId)) {
                for (GridCheck gridCheck : gridChecks) {


                    GridInfo str = gridInfoMapper.selectByPrimaryKey(gridCheck.getGridId());
//                if(!"0".equals(str.getUpperGrid())){
//                    strOne=Integer.parseInt(str.getUpperGrid());
//                }
                    if(str!=null){
                        Integer strOne=str.getGridId();
                        GridInfo gridInfo=gridInfoMapper.selectByPrimaryKey(strOne);
                        String upperGrid=gridInfo.getUpperGrid();
                        if(Integer.parseInt(upperGrid)!=0 ){
                            GridInfo gridInfo1=gridInfoMapper.selectByPrimaryKey(Integer.parseInt(upperGrid));
                            if (gridInfo1!=null){
                                gridCheck.setGridName(gridInfo1.getGridName());
                            }else {
                                gridCheck.setGridName("");
                            }
                            gridCheck.setUserName(usersMapper.getUsernameByUserId(gridCheck.getUserId()));
                        }else{
                            gridCheck.setGridName(gridInfoMapper.selectByPrimaryKey(strOne).getGridName());
                            gridCheck.setUserName(usersMapper.getUsernameByUserId(gridCheck.getUserId()));
                        }
                        gridCheckss.add(gridCheck);
                    }
                }
                for(int is=gridChecks.size()-1;is>=0;is--){
                    if(gridChecks.get(is).getUserName()==null || gridChecks.get(is).getGridName()==null){
                        gridChecks.remove(is);
                    }
                }
                baseWrappers.setTotal(total);
                baseWrappers.setFlag(true);
                //返回网格
                if(gridCheckss!=null&&gridCheckss.size()!=0){
                    for(GridCheck gridCheck:gridCheckss){
                        String deptid=gridCheck.getSubCommunity();
                        GridInfo gridInfo=gridInfoMapper.selectByPrimaryKey(Integer.parseInt(deptid));
                        gridCheck.setSubComunityStr(gridInfo.getGridName());
                    }
                }
                baseWrappers.setDatas(gridCheckss);

            } else {
                try {
                    HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("巡检信息", 9);
                    String[] secondTitles = {"巡检人员id", "巡查时间", "问题"};
                    HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

                    // String[] beanProperty = {user.getDep().getDeptName(),"userName","userPrivName", "roleAuxiliaryName","online","sex","online","telNoDept","telNoDept","departmentPhone","email"};
                    String[] beanProperty = {"userId", "checkTime", "location"};

                    HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, gridChecks, beanProperty);
                    ServletOutputStream out = response.getOutputStream();

                    String filename = "巡检信息导出.xls";
                    filename = FileUtils.encodeDownloadFilename(filename,
                            request.getHeader("user-agent"));
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("content-disposition",
                            "attachment;filename=" + filename);
                    workbook.write(out);
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

            }

        }
        baseWrappers.setFlag(true);

        return  baseWrappers;
    }

    //带权限的查询巡检记录
   public BaseWrappers selectqxList(HttpServletRequest request, HttpServletResponse response, String checkType,
                                    Integer page, Integer pageSize, boolean useFlag, String exportId, String gridName){
       BaseWrappers baseWrappers = new BaseWrappers();
       baseWrappers.setStatus(true);
       baseWrappers.setFlag(false);
       Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
       ToJson json = new ToJson(1,"error");
       page = (page - 1) * pageSize;
       Map<String, Object> map = new HashMap<String, Object>();
       map.put("page", page);
       map.put("pageSize", pageSize);
       Map<String, Object> param = new HashMap<String, Object>();
       param.put("userId", user.getUserId());
       param.put("userPriv", user.getUserPriv());
       param.put("deptId", user.getDeptId());
       String menuModel=menuJdtMapper.selMenuByModel("1");
       GridCheck gridCheck1=new GridCheck();
       if(!CheckAll.checkAll(menuModel,param)){
           map.put("userId",user.getUserId());
       }
       map.put("checkType",checkType);

      List<GridCheck> gridChecks=new ArrayList<>();
       gridChecks = gridCheckMapper.selWillGridSendOrReceive(map);
       int total = gridCheckMapper.selWillGridSendOrReceiveCounts(map);
       List<GridCheck> gridCheckss=new ArrayList<GridCheck>();
       if ("1".equals(exportId)) {
           for (GridCheck gridCheck : gridChecks) {
               GridInfo str = gridInfoMapper.selectByPrimaryKey(gridCheck.getGridId());
               if(str!=null){
                   Integer strOne=str.getGridId();
                   GridInfo gridInfo=gridInfoMapper.selectByPrimaryKey(strOne);
                   String upperGrid=gridInfo.getUpperGrid();
                   if(Integer.parseInt(upperGrid)!=0 ){
                       GridInfo gridInfo1=gridInfoMapper.selectByPrimaryKey(Integer.parseInt(upperGrid));
                       if (gridInfo1!=null){
                           gridCheck.setGridName(gridInfo1.getGridName());
                       }else {
                           gridCheck.setGridName("");
                       }
                       gridCheck.setUserName(usersMapper.getUsernameByUserId(gridCheck.getUserId()));
                   }else{
                       gridCheck.setGridName(gridInfoMapper.selectByPrimaryKey(strOne).getGridName());
                       gridCheck.setUserName(usersMapper.getUsernameByUserId(gridCheck.getUserId()));
                   }
                   gridCheckss.add(gridCheck);
               }
           }
           for(int is=gridChecks.size()-1;is>=0;is--){
               if(gridChecks.get(is).getUserName()==null || gridChecks.get(is).getGridName()==null){
                   gridChecks.remove(is);
               }
           }
           baseWrappers.setTotal(total);
           baseWrappers.setFlag(true);
           //返回网格
           if(gridCheckss!=null&&gridCheckss.size()!=0){
               for(GridCheck gridCheck:gridCheckss){
                   String deptid=gridCheck.getSubCommunity();
                   GridInfo gridInfo=gridInfoMapper.selectByPrimaryKey(Integer.parseInt(deptid));
                   gridCheck.setSubComunityStr(gridInfo.getGridName());
               }
           }
           baseWrappers.setDatas(gridCheckss);

       }
       baseWrappers.setFlag(true);

       return  baseWrappers;
   }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-12
     * 方法说明：登录本人的巡查记录
     *
     * @return
     */
    public BaseWrappers selectOwnList(HttpServletRequest request, HttpServletResponse response, String gridName, String checkType, String newsTime, String lastEditTime,
                                      String userId, String checkInfo, Integer page, Integer pageSize, String exportId) {
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        if(StringUtils.checkNull(userId)||"1".equals(userId)){
            userId=user.getUserId();
        }
        BaseWrappers baseWrappers = new BaseWrappers();
        baseWrappers.setStatus(true);
        baseWrappers.setFlag(false);
        page = (page - 1) * pageSize;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", userId);
        param.put("page", page);
        param.put("pageSize", pageSize);
        param.put("gridName", gridName);
        param.put("checkType", checkType);
        param.put("newsTime", newsTime);
        param.put("lastEditTime", lastEditTime);
        param.put("checkInfo", checkInfo);



        List<GridCheck> gridChecks = gridCheckMapper.selWillGridSendOrReceive(param);
        if (gridChecks != null && gridChecks.size() > 0) {
            for (GridCheck g : gridChecks) {
                if (g != null && !StringUtils.checkNull(g.getCheckType())) {
                    SysCode singleCode = sysCodeMapper.getSingleCode("GRID_CHECK", g.getCheckType());
                    g.setCheckType(singleCode.getCodeName());
                }
            }
        }

        if ("1".equals(exportId)) {
            for (GridCheck gridCheck : gridChecks) {
                GridInfo str = gridInfoMapper.selectByPrimaryKey(gridCheck.getGridId());
                Integer strOne=str.getGridId();
//                if(!"0".equals(str.getUpperGrid())){
//                    strOne=Integer.parseInt(str.getUpperGrid());
//                }
                gridCheck.setGridName(gridInfoMapper.selectByPrimaryKey(strOne).getGridName());

                gridCheck.setUserName(usersMapper.getUsernameByUserId(gridCheck.getUserId()));
            }
            int total = gridCheckMapper.selWillGridSendOrReceiveCounts(param);
            baseWrappers.setTotal(total);
            baseWrappers.setFlag(true);
            baseWrappers.setDatas(gridChecks);

        } else {
            try {
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("巡检信息", 9);
                String[] secondTitles = {"巡检人员id", "巡查时间", "问题"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

                // String[] beanProperty = {user.getDep().getDeptName(),"userName","userPrivName", "roleAuxiliaryName","online","sex","online","telNoDept","telNoDept","departmentPhone","email"};
                String[] beanProperty = {"userId", "checkTime", "location"};

                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, gridChecks, beanProperty);
                ServletOutputStream out = response.getOutputStream();

                String filename = "巡检信息导出.xls";
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

        }

        return baseWrappers;

    }

    public BaseWrappers checkStatistics(String timeType, String queryType, HttpServletRequest request) {
        BaseWrappers baseWrappers = new BaseWrappers();
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //权限判断
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        /*int qx=0;*/

        if (timeType.equals("day")) {
            long current = System.currentTimeMillis();//当前时间毫秒数
            long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
            long twelve = zero + 24 * 60 * 60 * 1000 - 1;//今天23点59分59秒的毫秒数
            map.put("startTime", sdf.format(zero));
            map.put("endTime", sdf.format(twelve));
        } else if (timeType.equals("week")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            // 获取星期一
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            long mondayTime = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
            // 获取星期日
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
            long sundayTime = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset() + 24 * 60 * 60 * 1000 - 1;

            map.put("startTime", sdf.format(mondayTime));
            map.put("endTime", sdf.format(sundayTime));
        } else if (timeType.equals("month")) {
            Calendar c = Calendar.getInstance();
            //设置为1号,当前日期既为本月第一天
            c.set(Calendar.DAY_OF_MONTH, 1);
            String first = sdf.format(c.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset());
            //获取当前月最后一天
            Calendar ca = Calendar.getInstance();
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            String last = sdf.format(ca.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset() + 24 * 60 * 60 * 1000 - 1);
            map.put("startTime", first);
            map.put("endTime", last);
        } else if (timeType.equals("year")) {
            Calendar calendar = Calendar.getInstance();

            calendar.set(Calendar.MONTH, 0);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            long first = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();

            calendar.set(Calendar.MONTH, 12);
            calendar.set(Calendar.DAY_OF_MONTH, -1);
            long last = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset() + 24 * 60 * 60 * 1000 - 1;

            map.put("startTime", sdf.format(first));
            map.put("endTime", sdf.format(last));
        }
        try {
            List<StatisticsModel> gridChecks = null;
            if ("grid".equals(queryType)) {
                map.put("field", "SUB_COMMUNITY");
                List<GridInfo> gridInfos = gridInfoMapper.gridSettingsTree("0");

                gridChecks = gridCheckMapper.checkStatistics(map);
                //去掉网格
                for(int t=gridChecks.size()-1;t>=0;t--){
                    if(gridChecks.get(t).getName()!=null && gridChecks.get(t).getName()!=""){
                        if(gridChecks.get(t).getName().indexOf("网格")!=-1){
                           // gridChecks.remove(t);
                            if(gridChecks.get(t).getId()!=null){
                                GridInfo gridInfo = gridInfoMapper.selectByPrimaryKey(Integer.valueOf(gridChecks.get(t).getId()));
                                String upperGrid=gridInfo.getUpperGrid();
                                if(Integer.parseInt(upperGrid)!=0){
                                    GridInfo gridInfo1=gridInfoMapper.selectByPrimaryKey(Integer.parseInt(upperGrid));
                                    gridChecks.get(t).setName(gridInfo1.getGridName());
                                }else{
                                    gridChecks.get(t).setName(gridInfo.getGridName());
                                }
                            }
                        }
                    }
                }
                if(gridInfos.size()!=gridChecks.size()){
                    for (GridInfo g:gridInfos){
                        Integer gridId = g.getGridId();
                        for(int i=0;i<gridChecks.size()+1;i++){
                            if(i<gridChecks.size()){
                                if(gridId.equals(gridChecks.get(i).getId())){
                                    break;
                                }
                            }else {
                                StatisticsModel statisticsModel = new StatisticsModel();
                                statisticsModel.setId(gridId.toString());
                                statisticsModel.setY(0);
                                statisticsModel.setName(g.getGridName());
                                statisticsModel.setData(new ArrayList<StatisticsModel>());
                                gridChecks.add(statisticsModel);
                                break;
                            }
                        }
                    }
                }

                for (StatisticsModel s : gridChecks) {
                    map.put("field", "user_id");
                    map.put("gridId", s.getId());
                    List<StatisticsModel> statisticsModels = gridCheckMapper.checkStatistics(map);
                    s.setData(statisticsModels);
                }
            } else {
                map.put("field", "check_type");
                List<SysCode> sysCodes = sysCodeMapper.getSysCode("GRID_CHECK");
                gridChecks = gridCheckMapper.checkStatisticsByType(map);

                if(sysCodes.size()!=gridChecks.size()){
                    for (SysCode sysCode:sysCodes){
                        String codeNo = sysCode.getCodeNo();
                        for(int i=0;i<gridChecks.size()+1;i++){
                            if(i<gridChecks.size()){
                                if(codeNo.equals(gridChecks.get(i).getId().toString())){
                                    break;
                                }
                            }else {
                                StatisticsModel statisticsModel = new StatisticsModel();
                                statisticsModel.setId(codeNo);
                                statisticsModel.setY(0);
                                statisticsModel.setName(sysCode.getCodeName());
                                statisticsModel.setData(new ArrayList<StatisticsModel>());
                                gridChecks.add(statisticsModel);
                                break;
                            }

                        }
                    }
                }
                for (StatisticsModel s : gridChecks) {
                    map.put("field", "user_id");
                    map.put("checkType", s.getId());
                    for (SysCode sysCode:sysCodes) {
                        if(s.getId().toString().equals(sysCode.getCodeNo())){
                            s.setName(sysCode.getCodeName());
                        }
                    }
                    List<StatisticsModel> statisticsModels = gridCheckMapper.checkStatisticsByType(map);
                    s.setData(statisticsModels);
                }
            }
            baseWrappers.setFlag(true);
            baseWrappers.setStatus(true);
            baseWrappers.setMsg("ok");
            baseWrappers.setDatas(gridChecks);
        } catch (Exception e) {
            e.printStackTrace();
            baseWrappers.setStatus(false);
            baseWrappers.setFlag(false);
            baseWrappers.setMsg("err");
        }

        /*if(user.getUserPriv()!=null){
            if(user.getUserPriv()==1 || user.getUserPriv()==2 || user.getUserPriv()==3 || user.getUserPriv()==6 || user.getUserPriv()==13 || user.getUserPriv()==93){
                //用户的全部权限

            }else {
                List<String> userIdList = new ArrayList<>();
                List<StatisticsModel> gridChecks = null;
                List<String> stringUserId = gridInfoMapper.sQqXselect(user.getUserId());
                if (stringUserId.size() == 0) {
                    userIdList.add(user.getUserId());
                    map.put("StringUser", userIdList);
                    if ("grid".equals(queryType)) {
                        map.put("field", "SUB_COMMUNITY");
                        gridChecks = gridCheckMapper.checkStatistics(map);
                    }

                } else {
                    String tmesim = "";
                    for (int cou = 0; cou < stringUserId.size(); cou++) {
                        if (stringUserId.get(cou) != null) {
                            if (!stringUserId.get(cou).toString().equals("''")) {
                                tmesim += stringUserId.get(cou);
                            }
                        }
                    }
                    String[] stringList = null;
                    if (tmesim != null) {
                        stringList = tmesim.split(",");
                    }
                    //数组去重复
                    List<String> list = new ArrayList<>();
                    for (int i = 0; i < stringList.length; i++) {
                        for (int j = i + 1; j < stringList.length; j++) {
                            if (stringList[i].equals(stringList[j])) {
                                j = ++i;
                            }
                        }
                        list.add(stringList[i]);
                    }
                    map.put("StringUser", list);
                    if ("grid".equals(queryType)) {
                        map.put("field", "SUB_COMMUNITY");
                        gridChecks = gridCheckMapper.checkStatistics(map);
                    }

                }
                try {

                    if ("grid".equals(queryType)) {
                        *//*map.put("field", "SUB_COMMUNITY");
                        map.put("userId",user.getUserId());*//*
                        List<GridInfo> gridInfos = gridInfoMapper.gridSettingsTree("0");

                        *//*gridChecks = gridCheckMapper.checkStatistics(map);*//*
                        if(gridInfos.size()!=gridChecks.size()){
                            for (GridInfo g:gridInfos){
                                Integer gridId = g.getGridId();
                                for(int i=0;i<gridChecks.size()+1;i++){
                                    if(i<gridChecks.size()){
                                        if(gridId.equals(gridChecks.get(i).getId())){
                                            break;
                                        }
                                    }else {
                                        StatisticsModel statisticsModel = new StatisticsModel();
                                        statisticsModel.setId(gridId.toString());
                                        statisticsModel.setY(0);
                                        statisticsModel.setName(g.getGridName());
                                        statisticsModel.setData(new ArrayList<StatisticsModel>());
                                        gridChecks.add(statisticsModel);
                                        break;
                                    }
                                }
                            }
                        }

                        for (StatisticsModel s : gridChecks) {
                            map.put("field", "user_id");
                            map.put("gridId", s.getId());
                            List<StatisticsModel> statisticsModels = gridCheckMapper.checkStatistics(map);
                            s.setData(statisticsModels);
                        }
                    } else {
                        map.put("field", "check_type");
                        map.put("userId",user.getUserId());
                        List<SysCode> sysCodes = sysCodeMapper.getSysCode("GRID_CHECK");
                        gridChecks = gridCheckMapper.checkStatisticsByType(map);

                        if(sysCodes.size()!=gridChecks.size()){
                            for (SysCode sysCode:sysCodes){
                                String codeNo = sysCode.getCodeNo();
                                for(int i=0;i<gridChecks.size()+1;i++){
                                    if(i<gridChecks.size()){
                                        if(codeNo.equals(gridChecks.get(i).getId().toString())){
                                            break;
                                        }
                                    }else {
                                        StatisticsModel statisticsModel = new StatisticsModel();
                                        statisticsModel.setId(codeNo);
                                        statisticsModel.setY(0);
                                        statisticsModel.setName(sysCode.getCodeName());
                                        statisticsModel.setData(new ArrayList<StatisticsModel>());
                                        gridChecks.add(statisticsModel);
                                        break;
                                    }

                                }
                            }
                        }
                        for (StatisticsModel s : gridChecks) {
                            map.put("field", "user_id");
                            map.put("checkType", s.getId());
                            for (SysCode sysCode:sysCodes) {
                                if(s.getId().toString().equals(sysCode.getCodeNo())){
                                    s.setName(sysCode.getCodeName());
                                }
                            }
                            List<StatisticsModel> statisticsModels = gridCheckMapper.checkStatisticsByType(map);
                            s.setData(statisticsModels);
                        }
                    }
                    for(int t=gridChecks.size()-1;t>=0;t--){
                        if(gridChecks.get(t).getName()!=null && gridChecks.get(t).getName()!=""){
                            if(gridChecks.get(t).getName().indexOf("网格")!=-1){
                                gridChecks.remove(t);
                            }
                        }
                    }
                    baseWrappers.setFlag(true);
                    baseWrappers.setStatus(true);
                    baseWrappers.setMsg("ok");
                    baseWrappers.setDatas(gridChecks);
                } catch (Exception e) {
                    e.printStackTrace();
                    baseWrappers.setStatus(false);
                    baseWrappers.setFlag(false);
                    baseWrappers.setMsg("err");
                }
            }
        }*/

        return baseWrappers;
    }



    public BaseWrappers getLastCheckMsg(){
        BaseWrappers baseWrapper = new BaseWrappers();
        List<GridCheck> lastCheckMsg = gridCheckMapper.getLastCheckMsg();
        baseWrapper.setDatas(lastCheckMsg);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    public BaseWrapper gridCheckCount(){
        BaseWrapper baseWrapper = new BaseWrapper();
       GridCheck lastCheckMsg = gridCheckMapper.gridCheckCount();

        lastCheckMsg.setGridCheckCount(strCount(lastCheckMsg.getCount3()));
        lastCheckMsg.setGridEevent1Count(strCount(lastCheckMsg.getCount2()));
        lastCheckMsg.setGridEeventCount(strCount(lastCheckMsg.getCount1()));
        baseWrapper.setData(lastCheckMsg);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

  public  String  strCount(Integer counrStr ){

        return  String.format("%05d", counrStr);
  }


    /**
     * 手机端查询分析统计接口
     * @return
     */
  public ToJson checkEvent(){
      ToJson json=new ToJson();
      Map<String,Object> map=new HashMap<String,Object>();
      Integer jinrInspection=gridCheckMapper.checkSelect();
      Integer jinrEvent=gridEventMapper.eventSelect();
      Integer jinrEventXiafa=gridEventMapper.eventSelectXiafa();
      Integer weekInspection=gridCheckMapper.checkSelectDay();
      Integer weekEvent=gridEventMapper.eventSelectDay();
      Integer weekEventXiafa=gridEventMapper.eventSelectDayXiafa();
      Integer monthInspection=gridCheckMapper.checkSelectModay();
      Integer monthEvent=gridEventMapper.eventSelectModay();
      Integer monthEventXiafa=gridEventMapper.eventSelectModayXiafa();
      map.put("jinrInspection",jinrInspection==null?0:jinrInspection);
      map.put("weekInspection",weekInspection==null?0:weekInspection);
      map.put("monthInspection",monthInspection==null?0:monthInspection);
      map.put("jinrEvent",jinrEvent==null?0:jinrEvent);
      map.put("jinrEventXiafa",jinrEventXiafa==null?0:jinrEventXiafa);
      map.put("weekEvent",weekEvent==null?0:weekEvent);
      map.put("weekEventXiafa",weekEventXiafa==null?0:weekEventXiafa);
      map.put("monthEvent",monthEvent==null?0:monthEvent);
      map.put("monthEventXiafa",monthEventXiafa==null?0:monthEventXiafa);
      json.setObject(map);
      json.setMsg("ok");
      json.setFlag(0);
      return json;
  }

    /**
     * 安卓端巡检查询方法
     * @return
     */
  public ToJson getStatisticsArrt(String timeType, String startTime, String endTime, HttpServletRequest request, String paixu){
      ToJson json=new ToJson();
              try{
                  BaseWrappers baseWrapper1=new BaseWrappers();
                  BaseWrappers baseWrapper=new BaseWrappers();
                  List<SysCode> sysCodes = sysCodeMapper.getSysCode("GRID_CHECK");
                  List<StatisticsModel> statisticsModelList1=new ArrayList<StatisticsModel>();
                  for(SysCode s:sysCodes){
                      StatisticsModel statisticsModel=new StatisticsModel();
                      statisticsModel.setName(s.getCodeName());
                      statisticsModel.setId(String.valueOf(s.getCodeId()));
                      Map<String,Object> map=new HashMap<String,Object>();
                      map.put("checkType",s.getCodeNo());
                      map.put("timeType",timeType);
                      map.put("startTime",startTime);
                      map.put("endTime",endTime);
                      List<StatisticsModel> statisticsModels=  gridCheckMapper.checkUpdateStatisticsType(map);
                      int total=0;
                      for(int i=0;i<statisticsModels.size();i++){
                          total+= statisticsModels.get(i).getY();
                      }
                      statisticsModel.setData(statisticsModels);
                      statisticsModel.setY(total);
                      statisticsModelList1.add(statisticsModel);

                  }

                          baseWrapper1.setDatas(statisticsModelList1);
                  {
                      List<Department> departmentList=departmentMapper.getDeptIdGridByParent("27");
                      List<StatisticsModel> statisticsModelList=new ArrayList<StatisticsModel>();
                      for (Department department:departmentList){
                          StatisticsModel statisticsModel=new StatisticsModel();
                          statisticsModel.setName(department.getDeptName());
                          statisticsModel.setId(String.valueOf(department.getDeptId()));
                          Map<String,Object> map=new HashMap<String,Object>();
                          map.put("depId",department.getDeptId());
                          map.put("timeType",timeType);
                          map.put("startTime",startTime);
                          map.put("endTime",endTime);
                          List<StatisticsModel> statisticsModels=  gridCheckMapper.checkUpdateStatistics(map);
                          int total=0;
                          for(int i=0;i<statisticsModels.size();i++){
                              total+= statisticsModels.get(i).getY();
                          }
                          statisticsModel.setData(statisticsModels);
                          statisticsModel.setY(total);
                          statisticsModelList.add(statisticsModel);
                      }
                      if(paixu!=null){
                          Collections.sort(statisticsModelList, new Comparator<StatisticsModel>() {
                              @Override
                              public int compare(StatisticsModel o1, StatisticsModel o2) {
                                  if(o1.getY()>o2.getY()){
                                      return -1;
                                  }
                                  if(o1.getY()==o2.getY()){
                                      return 0;
                                  }
                                  return 1;
                              }
                          });
                      }
                      baseWrapper.setDatas(statisticsModelList);
                  }

               Map<String,Object> map=new HashMap<String,Object>();
                  map.put("baseWrapper1",baseWrapper1);
                  map.put("baseWrapper",baseWrapper);
               json.setObject(map);
              json.setFlag(0);
              json.setMsg("ok");
          }catch (Exception e){
            e.printStackTrace();
          }
          return json;
  }

  public BaseWrappers selectGriChecki(HttpServletRequest request, String userName, Integer page, Integer pageSize, String timeType){
      Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
      Map<String, Object> map = new HashMap<String, Object>();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      List<GridCheck> gridChecks=new ArrayList<GridCheck>();
      BaseWrappers baseWrappers = new BaseWrappers();
      baseWrappers.setStatus(true);
      baseWrappers.setFlag(false);
      page = (page - 1) * pageSize;
      map.put("page", page);
      map.put("pageSize", pageSize);
      map.put("userName",userName);
      if (timeType.equals("day")) {
          long current = System.currentTimeMillis();//当前时间毫秒数
          long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
          long twelve = zero + 24 * 60 * 60 * 1000 - 1;//今天23点59分59秒的毫秒数
          map.put("startTime", sdf.format(zero));
          map.put("endTime", sdf.format(twelve));
      } else if (timeType.equals("week")) {
          Calendar calendar = Calendar.getInstance();
          calendar.setFirstDayOfWeek(Calendar.MONDAY);
          // 获取星期一
          calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
          long mondayTime = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
          // 获取星期日
          calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
          long sundayTime = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset() + 24 * 60 * 60 * 1000 - 1;

          map.put("startTime", sdf.format(mondayTime));
          map.put("endTime", sdf.format(sundayTime));
      } else if (timeType.equals("month")) {
          Calendar c = Calendar.getInstance();
          //设置为1号,当前日期既为本月第一天
          c.set(Calendar.DAY_OF_MONTH, 1);
          String first = sdf.format(c.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset());
          //获取当前月最后一天
          Calendar ca = Calendar.getInstance();
          ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
          String last = sdf.format(ca.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset() + 24 * 60 * 60 * 1000 - 1);
          map.put("startTime", first);
          map.put("endTime", last);
      } else if (timeType.equals("year")) {
          Calendar calendar = Calendar.getInstance();

          calendar.set(Calendar.MONTH, 0);
          calendar.set(Calendar.DAY_OF_MONTH, 1);
          long first = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();

          calendar.set(Calendar.MONTH, 12);
          calendar.set(Calendar.DAY_OF_MONTH, -1);
          long last = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset() + 24 * 60 * 60 * 1000 - 1;

          map.put("startTime", sdf.format(first));
          map.put("endTime", sdf.format(last));
      }
      gridChecks = gridCheckMapper.selectGriChecki(map);
      //去掉网格
      for(int t=gridChecks.size()-1;t>=0;t--){
          if(gridChecks.get(t).getGridName()!=null && gridChecks.get(t).getGridName()!=""){
              if(gridChecks.get(t).getGridName().indexOf("网格")!=-1){
                  // gridChecks.remove(t);
                  if(gridChecks.get(t).getGridId()!=null){
                      GridInfo gridInfo = gridInfoMapper.selectByPrimaryKey(Integer.valueOf(gridChecks.get(t).getGridId()));
                      String upperGrid=gridInfo.getUpperGrid();
                      if(Integer.parseInt(upperGrid)!=0){
                          GridInfo gridInfo1=gridInfoMapper.selectByPrimaryKey(Integer.parseInt(upperGrid));
                          gridChecks.get(t).setGridName(gridInfo1.getGridName());
                      }else{
                          gridChecks.get(t).setGridName(gridInfo.getGridName());
                      }
                  }
              }
          }
      }
      if(gridChecks.size()>0){
          baseWrappers.setDatas(gridChecks);
          baseWrappers.setTotal(gridChecks.size());
          return baseWrappers;
      }
        baseWrappers.setTotal(gridChecks.size());
        baseWrappers.setFlag(true);
        baseWrappers.setMsg("err");
      return baseWrappers;
  }
    public BaseWrappers checkUpdateStatistics(String timeType, String queryType, String startTime, String endTime, HttpServletRequest request, String typeDate) {
        BaseWrappers baseWrapper=new BaseWrappers();
        if("2".equals(queryType)){
            List<SysCode> sysCodes = sysCodeMapper.getSysCode("GRID_CHECK");
            List<StatisticsModel> statisticsModelList=new ArrayList<StatisticsModel>();
            for(SysCode s:sysCodes){
                StatisticsModel statisticsModel=new StatisticsModel();
                statisticsModel.setName(s.getCodeName());
                statisticsModel.setId(String.valueOf(s.getCodeId()));
                Map<String,Object> map=new HashMap<String,Object>();
                map.put("timeType",timeType);
                map.put("checkType",s.getCodeNo());
                map.put("startTime",startTime);
                map.put("endTime",endTime);
                map.put("typeDate",typeDate);
                map.put("dept",1);
                List<StatisticsModel> statisticsModels=  gridCheckMapper.checkUpdateStatisticsType(map);
                int total=0;
                for(int i=0;i<statisticsModels.size();i++){
                    total+= statisticsModels.get(i).getY();
                }
                statisticsModel.setData(statisticsModels);
                statisticsModel.setY(total);
                statisticsModelList.add(statisticsModel);

            }
            baseWrapper.setDatas(statisticsModelList);
        }else {
        List<Department> departmentList=departmentMapper.getDeptIdGridByParent("0");
        List<StatisticsModel> statisticsModelList=new ArrayList<StatisticsModel>();
        for (Department department:departmentList){
            StatisticsModel statisticsModel=new StatisticsModel();
            statisticsModel.setName(department.getDeptName());
            statisticsModel.setId(String.valueOf(department.getDeptId()));
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("timeType",timeType);
            map.put("depId",department.getDeptId());
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            List<StatisticsModel> statisticsModels=  gridCheckMapper.checkUpdateStatistics(map);
            int total=0;
            for(int i=0;i<statisticsModels.size();i++){
                 total+= statisticsModels.get(i).getY();
            }
            statisticsModel.setData(statisticsModels);
            statisticsModel.setY(total);
            statisticsModelList.add(statisticsModel);
         }
            baseWrapper.setDatas(statisticsModelList);
        }

        baseWrapper.setStatus(true);
        baseWrapper.setFlag(true);
        return baseWrapper;
    }
    public BaseWrappers gridByUserName  (String timeType, String startTime, String endTime, String userName, String gridIds, String type, String location, Integer page, Integer pageSize)throws Exception{
        BaseWrappers baseWrapper=new BaseWrappers();
        page = (page - 1) * pageSize;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("startTime",startTime);
        param.put("endTime",endTime);
        param.put("timeType",timeType);
        param.put("userName", userName);
        param.put("location",location);
        param.put("page", page);
        param.put("pageSize", pageSize);
        param.put("gridIds",gridIds);
        param.put("type",type);
        List<GridCheck> gridChecks = gridCheckMapper.gridByUserName(param);
        for (GridCheck g : gridChecks) {
            Integer gridId = Integer.parseInt(g.getSubCommunity());
            GridInfo gridInfo = gridInfoMapper.selectByPrimaryKey(gridId);
            if(Integer.parseInt(gridInfo.getUpperGrid())!=0){
                GridInfo gridInfo1 = gridInfoMapper.selectByPrimaryKey(Integer.parseInt(gridInfo.getUpperGrid()));
                g.setGridName(gridInfo1.getGridName());

            }
            if (g != null && !StringUtils.checkNull(g.getCheckType())) {
                SysCode singleCode = sysCodeMapper.getSingleCode("GRID_CHECK", g.getCheckType());
                g.setCheckType(singleCode.getCodeName());
            }

        }
        Integer total = gridCheckMapper.gridByUserNameConut(param);
        baseWrapper.setDatas(gridChecks);
        baseWrapper.setTotal(total);
        baseWrapper.setStatus(true);
        baseWrapper.setFlag(true);
        return baseWrapper;
    }
    /**
     * 创建人：季佳伟
     * 创建时间：2018-01-29
     * 方法说明：巡检统计按社区或人员排行榜
     *
     * @return
     */
    public BaseWrapper checkRank(String rankType, String timeType, String startTime, String endTime){
        BaseWrapper baseWrapper=new BaseWrapper();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar=Calendar.getInstance();
        //根据前端的参数，判断是哪种类型，
        Map<String,Object> map=new HashMap<String,Object>();
        try {
            if(timeType!=null&&timeType!=""){
                Date start=null;
                Date end=new Date();
                if (timeType.equals("month")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-1);
                    start=calendar.getTime();

                } else if (timeType.equals("threeMonth")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-3);
                    start=calendar.getTime();
                } else if (timeType.equals("halfYear")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-6);
                    start=calendar.getTime();

                } else if (timeType.equals("year")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.YEAR,-1);
                    start=calendar.getTime();
                }
                map.put("startTime", sdf.format(start));
                map.put("endTime", sdf.format(end));
            }else{
                String d = "";
                if (endTime != null && !"".equals(endTime)){
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    Date date=sdf1.parse(endTime);
                    Calendar calendar1  =  new GregorianCalendar();
                    calendar1.setTime(date);
                    calendar1.add(calendar1.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
                    date=calendar1.getTime();
                    d = DateFormat.getDatestr(date);
                }
                map.put("startTime", startTime);
                map.put("endTime", d);
            }
            if(rankType!=null&&rankType!=""){
                if ("1".equals(rankType)){
                    List<GridCheckRankModel> gridCheckRankModelList = gridCheckMapper.selectCheckRankByGrid(map);
                    baseWrapper.setData(gridCheckRankModelList);
                    baseWrapper.setMsg("ok");
                    baseWrapper.setFlag(true);
                    baseWrapper.setStatus(true);
                }
                if ("2".equals(rankType)){
                    List<GridCheckRankModel> gridCheckRankModelList = gridCheckMapper.selectCheckRankByUser(map);
                    baseWrapper.setData(gridCheckRankModelList);
                    baseWrapper.setMsg("ok");
                    baseWrapper.setFlag(true);
                    baseWrapper.setStatus(true);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return baseWrapper;
    }

    /**
     * 创建人：季佳伟
     * 创建时间：2018-01-28
     * 方法说明：巡检统计  社区或人员排行榜  一级穿透
     *
     * @return
     */
    public BaseWrapper checkRankListDetail(String rankType, Integer page, Integer pageSize, boolean useFlag,
                                           String gridId, String userId, String timeType, String startTime, String endTime){
        BaseWrapper baseWrapper=new BaseWrapper();
        Map<String,Object> map=new HashMap<String,Object>();
        Map<String,Object> map1=new HashMap<String,Object>();
        PageParams pageParams=new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("pageParams",pageParams);
        try {
            Calendar calendar=Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(timeType!=null&&timeType!=""){
                Date start=null;
                Date end=new Date();
                if (timeType.equals("month")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-1);
                    start=calendar.getTime();

                } else if (timeType.equals("threeMonth")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-3);
                    start=calendar.getTime();
                } else if (timeType.equals("halfYear")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-6);
                    start=calendar.getTime();

                } else if (timeType.equals("year")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.YEAR,-1);
                    start=calendar.getTime();
                }
                map.put("startTime", sdf.format(start));
                map.put("endTime", sdf.format(end));
                map1.put("startTime", sdf.format(start));
                map1.put("endTime", sdf.format(end));
            }else{
                String d = "";
                if (endTime != null && !"".equals(endTime)){
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    Date date=sdf1.parse(endTime);
                    Calendar calendar1  =  new GregorianCalendar();
                    calendar1.setTime(date);
                    calendar1.add(calendar1.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
                    date=calendar1.getTime();
                    d = DateFormat.getDatestr(date);
                }

                map.put("startTime", startTime);
                map.put("endTime", d);
                map1.put("startTime", startTime);
                map1.put("endTime", d);
            }
            if(rankType!=null&&rankType!=""){
                if ("1".equals(rankType)){
                    map.put("gridId",gridId);
                    List<GridCheckRankModel> list = gridCheckMapper.getRankTwoByGrid(map);
                    if(list!=null && list.size()>0){
                        baseWrapper.setData(list);
                        baseWrapper.setFlag(true);
                        baseWrapper.setMsg("ok");
                    }
                    return  baseWrapper;
                }
                if ("2".equals(rankType)){
                    map.put("userId",userId);
                    map1.put("userId",userId);
                    List<GridCheck> gridCheckList = gridCheckMapper.getRankTwoByUser(map);
                    baseWrapper.setData(gridCheckList);
                    baseWrapper.setTotle(gridCheckMapper.getCountRankTwoByUser(map1));
                    baseWrapper.setFlag(true);
                    baseWrapper.setMsg("ok");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return baseWrapper;
    }

    /**
     * 创建人：季佳伟
     * 创建时间：2018-01-28
     * 方法说明：巡检统计  排行榜  二级穿透
     *
     * @return
     */
    public BaseWrapper getThreeDetail(Integer page, Integer pageSize, boolean useFlag,
                                      String timeType, String gridId, String userId, String startTime, String endTime){
        BaseWrapper baseWrapper=new BaseWrapper();
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> map1=new HashMap<String,Object>();
        PageParams pageParams=new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("pageParams",pageParams);
        try {
            Calendar calendar=Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(timeType!=null&&timeType!=""){
                Date start=null;
                Date end=new Date();
                if (timeType.equals("month")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-1);
                    start=calendar.getTime();

                } else if (timeType.equals("threeMonth")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-3);
                    start=calendar.getTime();
                } else if (timeType.equals("halfYear")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.MONTH,-6);
                    start=calendar.getTime();

                } else if (timeType.equals("year")) {
                    calendar.setTime(end);
                    calendar.add(Calendar.YEAR,-1);
                    start=calendar.getTime();
                }
                map.put("startTime", sdf.format(start));
                map.put("endTime", sdf.format(end));
                map1.put("startTime", sdf.format(start));
                map1.put("endTime", sdf.format(end));
            }else{
                String d = "";
                if (endTime != null && !"".equals(endTime)){
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    Date date=sdf1.parse(endTime);
                    Calendar calendar1  =  new GregorianCalendar();
                    calendar1.setTime(date);
                    calendar1.add(calendar1.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
                    date=calendar1.getTime();
                    d = DateFormat.getDatestr(date);
                }
                map.put("startTime", startTime);
                map.put("endTime", d);
                map1.put("startTime", startTime);
                map1.put("endTime", d);
            }
            map.put("gridId",gridId);
            map.put("userId",userId);
            map1.put("gridId",gridId);
            map1.put("userId",userId);
            List<GridCheck> gridCheckList = gridCheckMapper.getRankThreeByGrid(map);
            baseWrapper.setData(gridCheckList);
            baseWrapper.setTotle(gridCheckMapper.getCountRankThreeByGrid(map1));
            baseWrapper.setFlag(true);
            baseWrapper.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
        }


        return baseWrapper;

    }
}
